package com.douguo.recipe.sina;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.util.Log;

class MemoryCache {

	/**
	 * 容量
	 */
	public static int CAPACITY = 1024 * 20;

	private static HashMap<String, Object> cache = new HashMap<String, Object>();

	private static int size;

	private static final Object lock = new Object();

	public static Object getCache(String key) {
		CacheEntity entity = (CacheEntity) cache.get(key);
		if (entity != null) {
			return entity.getObject();
		}
		return null;
	}

	public static void addCache(String key, Object value) {
		cache.put(key, new CacheEntity(key, value));
		// if (value instanceof Bitmap) {
		// size += getBitmapSize((Bitmap) value);
		// if (size >= CAPACITY) {
		// recycle();
		// }
		// }
	}

	private static int getBitmapSize(Bitmap bitmap) {
		int time = 2;
		Config con = bitmap.getConfig();
		if (con.equals(Config.ARGB_8888)) {
			time = 4;
		}
		return bitmap.getHeight() * bitmap.getWidth() * time;
	}

	private static void recycle() {
		ArrayList<CacheEntity> list = new ArrayList<CacheEntity>();

		synchronized (lock) {
			Iterator<Entry<String, Object>> iter = cache.entrySet().iterator();
			while (iter.hasNext()) {
				Entry<String, Object> entry = iter.next();
				String key = (String) entry.getKey();
				CacheEntity val = (CacheEntity) entry.getValue();

				list.add(val);
			}
		}

		Collections.sort(list);

		synchronized (lock) {
			while (size >= CAPACITY && list.size() > 0) {
				CacheEntity entity = list.remove(0);
				if (!(entity.getObject() instanceof Bitmap)) {
					continue;
				}

				size -= getBitmapSize((Bitmap) entity.getObject());
				Log.w("UMessage", "Delete Size : " + size);
				remove(entity.key);
			}
		}
	}

	public static Object remove(String key) {
		CacheEntity entity = (CacheEntity) cache.remove(key);
		if (entity != null) {
			return entity.getObject();
		}
		return null;
	}

}
